// buy_form.js
var app = getApp()
//常量数据配置
var ConstantData = require('../../../../common/constant_data.js')
var common = require("../../../../common/common.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    card_number:'',
    buy_type:0,
    tag:'',
    phone:'',
    pcode:'',
    tag:'',
    alertBoxStatus:false,
    VerifyCode:"获取验证码",
    btnName:'去付款',
    tipStatus:false,
    noPayTimeLen:0,
    noPayTimeLenStr:'',
    cardTimeLen:0,
    payCount:0,
    tipInfo:'',
    cardType:0,
    tipShowStatus:false,
    alertType:0,//弹框提示类型，0确认后跳转首页,1弹框消失
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("----buyBindForm---->")
    console.log(options)

    var cardNumber = options.cn
    var buyType = options.bt
    var noPayTimeLen = options.noPayTimeLen
    var cardTimeLen = options.cardTimeLen
    var cardType = options.cardType


    var tag = ''
    var btnName = '去付款'
    var tipInfo = ''
    var tipShowStatus = false
    if(buyType == 0) {
        //去绑定
        if (options.tag != null && options.tag != 'null') {
          tag = options.tag
        }        
        btnName = '绑定'
        var cardPhone = options.cardPhone
        var cardRemarks = options.cardRemarks
        tipInfo = getNoPayTimeTipInfo(cardTimeLen, noPayTimeLen,buyType,cardPhone,cardRemarks)
        tipShowStatus = true
    } else if (buyType == 1) {
        //自己购买  
      tipInfo = getNoPayTimeTipInfo(cardTimeLen, noPayTimeLen, buyType,'','')
        if(noPayTimeLen > 0) {
          tipShowStatus = true
        }
    } else if (buyType == 2) {
       //代他人购买，填写手机号获取验证码后可以得到提示信息
      noPayTimeLen = 0
    }
   

    this.setData({
      card_number:cardNumber,
      buy_type:buyType,
      tag:tag,
      btnName:btnName,
      noPayTimeLen: noPayTimeLen,
      cardTimeLen: cardTimeLen,
      cardType: cardType,
      tipInfo: tipInfo,
      tipShowStatus: tipShowStatus
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    if (this.data.alertBoxStatus) {
      this.setData({
        alertBoxStatus:false,
        alertType: 0
      })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  /**
   * 输入备注信息
   */
  setTag:function(e) {
    this.data.tag = e.detail.value
  },
  /**
   * 输入手机号
   */
  setPhonenum:function(e) {
    this.data.phone = e.detail.value
  },
  /**
   * 输入验证码
   */
  setPcode:function(e) {
    this.data.pcode = e.detail.value
  },
  getPhoneCode:function(){
    var that = this

     console.log("---phonenum=" + this.data.phonenum)
     if (this.data.phone != '') {
       var total_micro_second = 60 * 1000;
       //验证码倒计时
       count_down(this, total_micro_second);
       var phonenum = this.data.phone;

       app.executeRequest(function (header) {

         wx.request({
           url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/message/bindcard',
           header: header,
           data: {
             phonenum: phonenum,
             backType: 1,
             cardType: that.data.cardType
           },
           success: function (res) {
             var cardTimeLen = that.data.cardTimeLen
             var noPayTimeLen = res.data.data
             var buyType = that.data.buy_type
             var tipInfo = getNoPayTimeTipInfo(cardTimeLen, noPayTimeLen, buyType, '', '')
             var tipShowStatus = false
             if (noPayTimeLen && noPayTimeLen > 0) {
               tipShowStatus = true
             }
             that.setData({
               tipInfo: tipInfo,
               noPayTimeLen: noPayTimeLen,
               tipShowStatus: tipShowStatus
             })
             console.log("发送短信成功")
             console.log(res)
           },
           fail: function (res) {
             console.log("发送短信失败")
             console.log(res)
           }
         })

       })
       
     } else {
       wx.showToast({
         title: '请输入手机号'
       })
     }


  },
  /**
   * 发起购买卡请求或绑定卡请求
   */
  buyCard:function() {
    var that = this

    var buyType = that.data.buy_type    
    console.log("buyCard-------"+buyType)

    if(buyType == 0) {    
      //进行绑定操作
      that.bindCard()
    }else {
      //进行支付
      that.payCard()
    }
   
  },
  /**
   * 支付包时卡订单
   */
  payCard:function(){
    var that = this
    var buyType = that.data.buy_type

    if (!that.data.tag) {      
      that.setData({
        alertBoxStatus: true,
        alertBoxTipContent: '请输入患者信息',
        alertBoxBtnName: '确 定',
        alertType:1
      })
      return
    }

    //代购买
    if(buyType == 2) {
      if (that.data.phone == '') {        
        that.setData({
          alertBoxStatus: true,
          alertBoxTipContent: '请输入手机号',
          alertBoxBtnName: '确 定',
          alertType: 1
        })
        return
      }
      if (that.data.pcode == '') {        
        that.setData({
          alertBoxStatus: true,
          alertBoxTipContent: '请输入短信码',
          alertBoxBtnName: '确 定',
          alertType: 1
        })
        return
      }
    }    

    

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_time_card/buy_card',
        header: header,
        data: {
          cn: that.data.card_number,
          buyType: that.data.buy_type,
          tag: that.data.tag,
          phone: that.data.phone,
          pcode: that.data.pcode
        },
        success: function (res) {
          console.log("-----------buyCard--getOrderCode---")
          console.log(res)
          var rst = res.data.result
          if (rst == 0) {
            var orderCode = res.data.data
            that.toPay(orderCode)
          } else {
            var desc = res.data.description
            wx.showToast({
              title: desc + '(' + rst + ')',
            })
          }

        },
        fail: function (res) {
          wx.showToast({
            title: '稍后重试',
          })
        }
      })

    })    

  },
  /**
   * 绑定包时卡信息
   */
  bindCard:function() {
    var that = this 

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_time_card/bind',
        header: header,
        data: {
          cn: that.data.card_number,
          tag: that.data.tag
        },
        success: function (res) {
          var rst = res.data.result
          var desc = res.data.description
          //绑定成功
          if (rst == 0) {
            that.setData({
              alertBoxStatus: true,
              alertBoxTipContent: '绑定成功,到首页扫码即可为他(她)代租',
              alertBoxBtnName: '确 定'
            })
          } else {
            wx.showToast({
              title: desc,
            })
            console.log(res.data)
          }
        },
        fail: function (res) {
          wx.showToast({
            title: '稍后重试',
          })
          console.log(res.data)
        }
      })

    })    

  },
  /**
   * 提示框确认处理
   */
  alertBoxBtnClick:function(){     
     if (this.data.alertType == 0) {
       wx.redirectTo({
         url: '../../../../pages/index/index',
       })
     }
     this.setData({
       alertBoxStatus: false,
       alertType:0
     })
     
  },
  /**
   * 调用微信进行支付
   */
  toPay:function(orderCode) {

    var that = this
    console.log("去支付。。。" + orderCode)
    app.toPayValideLogin(orderCode, function(loginCode, orderCode, err){

      app.executeRequest(function (header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/weixin/pay',
          header: header,
          data: {
            orderCode: orderCode,
            loginCode: loginCode,
            wxErr: err
          },
          success: function (res) {
            var data = res.data
            console.log("支付结果---" + data.result)
            if (data.result != 0 || !data.data || !data.data.timeStamp) {
              that.setData({
                alertBoxStatus: true,
                alertBoxTipContent: data.description ? data.description:"支付失败"
              })
              return
            }
            //开始微信支付
            wx.requestPayment({
              appId: 'wx0e458dc331e557cc',
              timeStamp: data.data.timeStamp,
              nonceStr: data.data.nonceStr,
              package: data.data.package,
              signType: data.data.signType,
              paySign: data.data.paySign,
              success: function (res) {
                console.log("SUCCESS")
                console.log(res)
                //支付成功
                wx.showToast({
                  title: '支付成功',
                })
                wx.navigateTo({
                  url: '../../../../pages/index/index',
                })
              },
              fail: function (res) {
                common.recordErrorInfo(ConstantData.err_type.pay_fail, res ? 'buyForm-' + JSON.stringify(res) : '');
              },
              complete: function (res) {
                console.log("complete--" + data.data.paySign)
                console.log(res)
              }
            })
          }
        })
  
      })   

    })

  }
})



function count_down(that, total_micro_second) {
  if (total_micro_second <= 0) {
    that.setData({
      VerifyCode: "重新发送"
    });
    // timeout则跳出递归
    return;
  }
  // 渲染倒计时时钟
  that.setData({
    VerifyCode: date_format(total_micro_second) + " 秒"
  });
  setTimeout(function () {
    // 放在最后--
    total_micro_second -= 1000;
    count_down(that, total_micro_second);
  }, 1000)
}

// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function date_format(micro_second) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  // 小时位
  var hr = Math.floor(second / 3600);
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - hr * 3600 - min * 60));// equal to => var sec = second % 60;
  // 毫秒位，保留2位
  var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));
  return sec;
}
// 位数不足补零
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}

function getNoPayTimeTipInfo(cardTimeLen, noPayTimeLen, buyType,cardPhone, cardRemarks) {  
  var payCount = 1
  var noPayTimeLenStr = ''
  if (cardTimeLen < noPayTimeLen) {
    payCount = Math.ceil(noPayTimeLen / cardTimeLen)
  }
  if (noPayTimeLen >= 60) {
    noPayTimeLenStr = parseInt(noPayTimeLen / 60) + '小时'
  } else {
    noPayTimeLenStr = noPayTimeLen + '分钟'
  }
  var showStr = ''
  if(buyType == 0) {
    var cardTimeLenStr = cardTimeLen < 60 ? cardTimeLen + '分钟' : cardTimeLen/60 +'小时'    
    //绑卡
    return cardPhone+'('+cardRemarks+")的包时卡剩余时长是" + cardTimeLenStr + ",少于5小时请及时提醒家属再购买"
  }
  if(payCount > 1) {
    return "你有未支付的租金(租赁时长:"+noPayTimeLenStr+"),需要购买"+payCount+"份才能完成租金支付。"
  }  
  return "你有未支付的租金(租赁时长:" + noPayTimeLenStr+"),包时卡购买成功后会自动扣除抵扣"
}